// components/orderSheet/unpaidOrderItem.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    //订单编号
    orderNo: {
      type: String,
      value: ''
    },
    apply_no: {
      type: String,
      value: ''
    },

  },

  /**
   * 组件的初始数据
   */
  data: {
    imgPath: '/images',
    //剩余时间
    leftTime: '已退款',
    //结束时间
    endTime: '2022-11-17',
    orderItems: [{
      itemId: '1',
      itemNum: 1,
      itemImgSrc: '/cart/item.jpg',
      itemName: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
      itemDescrition: '尺寸：L',
      itemPrice: '138.00'
    }, {
      itemId: '2',
      itemNum: 1,
      itemImgSrc: '/cart/item.jpg',
      itemName: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
      itemDescrition: '尺寸：L',
      itemPrice: '138.00'
    }],
    //价钱合计
    totalPrice: 0,
    //订单详情
    detail: null,

    //显示寄回输入框
    showSendView: false,

    //物流公司名称
    logisticsCompany: '',
    //物流公司标识
    logisticsCompanyId: '',
    //物流公司列表
    logisticsCompanyList: [],

    //显示选择公司
    showSelCompany:false,
    //默认选中项
    selIndex:0,

    //物流单号
    logisticsNo:'',
  },

  /**
   * 组件的方法列表
   */
  methods: {

    // 订单详情
    goo_details(sun){
       console.log(32323);
    },

    /**
     * 整数小于10开头加0
     * @param {Number} d 数值
     */
    addZeroHead(d) {
      if (d < 10) return '0' + d;
      return d;
    },
    /**
     * 计算总价
     */
    calTotalPrice() {
      // let num = 0.0;
      // for (let item of this.data.orderItems) {
      //   num += Number(item.itemPrice);
      // }
      // console.log("num", num)
      this.setData({
        totalPrice: Number(this.data.detail.price).toFixed(2)
      })
    },

    /**
     * 立即支付
     * @param {*} e 
     */
    buyAgain(e) {
      this.triggerEvent("buyAgain", this.data.orderNo)
      let goods = this.data.detail.goods_info[0];
      if (goods) {
        if(goods.goods_type == 100){
          wx.navigateTo({
            url: '/pages/plan/joinPlan',
          })
          return;
        } 
        //跳转
        wx.navigateTo({
          url: '/pages/goods/detail?goods_id=' + goods.goods_id,
        })
      } else {
        wx.showToast({
          title: '商品不存在',
        })
      }
    },
    /**
     * 处理详情
     * @param {*} data 
     */
    handleDetail(data) {
      const that = this;

      // console.log("data",data)

      //订单项
      let orderItems = [];
      for (const item of data.goods_info) {
        orderItems.push({
          itemId: item.goods_id,
          itemNum: item.buy_number,
          itemImgSrc: item.image,
          itemName: item.goods_name,
          itemDescrition: item.stock_info.spec_value_name,
          itemPrice: item.price,
        })
      }

      //状态
      that.setData({
        endTime: data.complate_pay_time,
        orderItems: orderItems,
      })

      //设置一个定时器，计算付款剩余时间
      // that.calLeftTime();

      //计算总价
      that.calTotalPrice()

      // console.log("afterServiceOrderItem,orderDetail,that.data", that.data)

      //状态：1 申请中，2 已审核，3 已处理完成，4 审核不通过
      let status = '';
      switch (this.data.detail.after_sale_info.status) {
        case 1:
          status = "申请中"
          break;
        case 2:
          status = "已审核"
          break;
        case 3:
          status = "已处理完成"
          break;
        case 4:
          status = "审核不通过"
          break;
      }

      //订单号
      this.setData({
        orderNo: this.data.detail.order_sn,
        leftTime: status,
        apply_no: this.data.detail.after_sale_info.apply_no,
      })
    },
    /**
     * 输入寄回信息
     */
    saveSendBackNo() {
      this.setData({
        showSendView: true,
      })
    },
    onSyClose() {
      this.setData({
        showSendView: false
      })
    },
    /**
     * 开始选择公司
     */
    selCompany() {
      this.setData({
        showSelCompany:true,
      })
    },
    /**
     * 选中公司
     */
    onSelCompanyChange(e){
      console.log("onSelCompanyChange,e",e)
      let index=e.detail.index;
      this.setData({
        logisticsCompany:this.data.logisticsCompanyList[index].text,
        logisticsCompanyId:this.data.logisticsCompanyList[index].value,
        selIndex:index,
      })
      console.log("this.data",this.data)
    },
    cancelSel(){
      this.setData({
        logisticsCompany:"",
        logisticsCompanyId:'',
        showSelCompany:false,
      })
    },
    okSel(){
      this.setData({
        logisticsCompany:this.data.logisticsCompanyList[this.data.selIndex].text,
        logisticsCompanyId:this.data.logisticsCompanyList[this.data.selIndex].value,
      })
      //关闭选择框
      this.setData({
        showSelCompany:false,
      })
    },
    /**
     * 初始化物流公司
     */
    initLogisticsCompanyList() {
      const that = this;

      const api = require("../../api/api")
      api.afterSale.getLogisticsCom({
        success(res) {
          console.log("getLogisticsCom,res", res)
          let rows = res.data.data;

          that.data.logisticsCompanyList = [];
          for (const item of res.data.data) {
            that.data.logisticsCompanyList.push({
              text: item.value,
              value: item.key,
            })
          }

          that.setData({
            logisticsCompanyList: that.data.logisticsCompanyList,
          })
        }
      })
    },
    /**
     * 提交回单
     */
    sendBack(){
      // if(this.data.logisticsCompanyId==""){
      //   wx.showToast({
      //     title: '请选择物流公司',
      //     icon:'none',
      //   })
      //   return;
      // }

      if(this.data.logisticsNo==""){
        wx.showToast({
          title: '请输入物流单号',
          icon:'none',
        })
        return;
      }

      const api=require("../../api/api")
      console.log("this.data.detail",this.data.detail);
      //售后标识（单号）
      let apply_no=this.data.detail.after_sale_info.apply_no;
      console.log('apply_noapply_no',apply_no);
      api.afterSale.saveSendBackNo({
        // after_sale_id:apply_no,
        // logistics_com:this.data.logisticsCompanyId,
        // logistics_nu:this.data.logisticsNo,
        apply_no:apply_no,
        logistics_nu:this.data.logisticsNo,
        success(res){
          console.log("saveSendBackNo,res",res)

          if(res.data.code==0){
          wx.showToast({
            title: '提交成功',
          })

          //关闭弹窗
          this.setData({
            showSendView:false,
            showSendView:false,
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'error'
          })
        }
        }
      })
    },
  },
  lifetimes: {
    attached() {
      const that = this;

      console.log("apply_no,apply_no,apply_no", that.data.apply_no)
      
      //图片路径
      const util = require("../../utils/util")
      this.setData({
        imgPath: util.getImgPath()
      })

      //从缓存取出orderList，如果有，直接使用
      let orderList = wx.getStorageSync('orderList')
      // console.log("orderList", orderList)
      if (!orderList) {

        //取订单详情
        const api = require("../../api/api")
        api.user.orderDetail({
          order_sn: this.data.orderNo,
          success(res) {
            // console.log("afterServiceOrderItem,orderDetail,res", res)

            let data = res.data.data;

            //保存订单详情
            that.setData({
              detail: data
            });

            //处理详情
            this.handleDetail(data);
          }
        })
      } else {
        let data;
        for (let item of orderList) {
          if (item.order_sn == this.data.orderNo) {
            data = item;
            break;
          }
        }

        //保存详情数据
        that.setData({
          detail: data
        })

        //处理详情
        this.handleDetail(data);
      }

      //计算总价
      // this.calTotalPrice()

      //初始化物流公司
      this.initLogisticsCompanyList();
    }
  }
})